<template>
  <div>
    <el-row class="page_top">
      <el-col :span="6">
        <el-form :model="search">
          <el-form-item prop="customerName">
            <el-autocomplete
              :fetch-suggestions="querySearchAsync"
              placeholder="请输入客户姓名"
              @select="handleSelect"
              v-model="search.customerName"
              clearable
              @clear="cleanSearch"
              ref="elautocomplete"
            >
              <template slot-scope="{ item }">
                <span>{{ item.label }}</span>
                <span v-show="false">{{ item.value }}</span>
              </template>
              <template slot="append">
                <el-button slot="append" icon="el-icon-search" @click="searchByCus"></el-button>
              </template>
            </el-autocomplete>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="18">
        <el-button type="primary" size="small" @click="addOpt" class="btn_add" icon="el-icon-setting">配置</el-button>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="6" class="options_box" v-for="(item, index) in cusOpts" :key="index">
        <div class="info">
          <div class="icons">
            <i class="el-icon-edit-outline" @click="edit(item)"></i>
            <i class="el-icon-delete" @click="del(item.t_no)"></i>
          </div>
          <div class="info_list">
            <ul>
              <li>客户姓名：{{item.t_name }}</li>
              <li>护照编号：{{item.t_no}}</li>
              <li>出发日期：{{item.PASSENGER_DATE | filterTime }}</li>
              <li>航班路线：{{item.PASSENGER_FROM | cityName }} - {{item.PASSENGER_TO | cityName}}</li>
              <li>机舱类型：{{item.PASSENGER_CLASS}}</li>
              <li>推送短信：{{item.t_tell}}</li>
              <li>推送邮箱：{{item.t_email}}</li>
              <li>登录账户：{{item.AGENT_USERNAME}}</li>
              <li>登录密码：{{item.AGENT_PASSWORD}}</li>
            </ul>
          </div>
        </div>
      </el-col>
    </el-row>
    <!-- 弹窗 新增or修改 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogShow" fullscreen>
      <!-- 添加/修改表单 -->
      <el-form label-width="100px" ref="customer" :model="customer">
        <el-row>
          <el-col :span="12">
            <el-row>
              <el-col :span="24">
                <el-form-item label="客户名称" prop="cuslist">
                  <el-select v-model="customer.cuslist" placeholder="请选择" filterable style="width:100%;" :disabled="isEdit">
                    <el-option
                      v-for="item in allDatas.cusl"
                      :key="item.id"
                      :label="item.PASSENGER_LASTNAME + item.PASSENGER_FIRSTNAME"
                      :value="item.id + ',' + item.PASSENGER_LASTNAME + item.PASSENGER_FIRSTNAME + ',' + item.PASSENGER_PASSPORT">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="登录账户" prop="t_logos">
                  <el-select v-model="customer.t_logos" placeholder="请选择" filterable style="width:100%;">
                    <el-option
                      v-for="item in allDatas.logl"
                      :key="item.id"
                      :label="item.AGENT_USERNAME"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
               <el-col :span="24">
                <el-form-item label="IP资源池" prop="t_url">
                   <el-select v-model="customer.t_url" placeholder="请选择" filterable style="width:100%;">
                    <el-option
                      v-for="item in allDatas.ipl"
                      :key="item.id"
                      :label="item.ips_name"
                      :value="item.SERVER_URL">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="12">
            <el-row>
             <el-col :span="24">
                <el-form-item label="邮件推送" prop="t_email">
                 <el-select v-model="customer.t_email" multiple placeholder="请选择" filterable style="width:100%;">
                    <el-option
                      v-for="item in allDatas.email"
                      :key="item.id"
                      :label="item.t_email"
                      :value="item.t_email">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="短信推送" prop="t_tell">
                  <el-select v-model="customer.t_tell" multiple placeholder="请选择" filterable style="width:100%;">
                    <el-option
                      v-for="item in allDatas.msgl"
                      :key="item.id"
                      :label="item.t_tell"
                      :value="item.t_tell">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button type="primary" size="small" v-if="dialogTitle === '添加'" @click="create">确认</el-button>
        <el-button size="small" v-else @click="update">修改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import code from "../../../static/cityCode.json";
import { get, post } from "../../http/index";
import moment from "moment";

export default {
  name: "customer",
  data() {
    return {
      // 是否修改
      isEdit: false,
      // 初始数据
      cusOpts: [],

      allDatas: {},
      // 查询条件
      search: {
        PASSENGER_PASSPORT: "",
        customerName: ""
      },

      // 远程搜索
      restaurants: [],
      // 计时器
      timeout: null,

      // 弹窗标题
      dialogTitle: "",
      // 弹窗是否显示
      dialogShow: false,

      customer: {
        cuslist: "",
        t_logos: "",
        t_url: "",
        t_email: [],
        t_tell: []
      }
    };
  },
  // 加载实例后执行
  mounted() {
    this.getAllDatas();
    // 获取所有客户配置文件
    this.searchAll();
  },
  filters: {
    filterTime: value => {
      return moment(value).format("YYYY-MM-DD");
    },
    cityName: value => {
      for (let i = code.cities.length; i--; ) {
        if (code.cities[i][4] === value) {
          return (
            code.cities[i][6] +
            code.cities[i][5] +
            code.cities[i][0] +
            "[" +
            code.cities[i][4] +
            "]"
          );
        } else {
          for (let j = code.cities[i][11].length; j--; ) {
            if (code.cities[i][11][j][2] === value) {
              return (
                code.cities[i][6] +
                code.cities[i][5] +
                code.cities[i][11][j][4] +
                "[" +
                code.cities[i][11][j][2] +
                "]"
              );
            }
          }
        }
      }
    }
  },
  methods: {
    getCus() {
      return post("/api/customer/getCustomerAll", { mark: 1 })
    },

    getLogos() {
      return post("/api/logos/getLogosAll", { mark: 1 })
    },

    getEmails() {
      return post("/api/emails/getEmailsAll", { mark: 1 })
    },

    getMessages() {
      return post("/api/message/getMessageAll", { mark: 1 })
    },

     getIps() {
      return post("/api/ips/getIpsAll", { mark: 1 })
    },

    getAllDatas() {
      let _this = this;
      let params = [_this.getCus(), _this.getLogos(), _this.getEmails(), _this.getMessages(), _this.getIps()]
      _this.$axios.all(params).then(_this.$axios.spread((cus, loglist, emailist, msglist, iplist) => {
        let datas = {
          cusl: cus.data,
          logl: loglist.data,
          email: emailist.data,
          msgl: msglist.data,
          ipl: iplist.data
        }
        _this.allDatas = datas;
        _this.pushCus(_this.allDatas.cusl);
      })).catch(err => {
        console.log(err);
      });
    },

    pushCus(data) {
      let _this = this;
      let list = [];
      for (let i = data.length; i--; ) {
        list.push({
          value: data[i].PASSENGER_PASSPORT,
          label: data[i].PASSENGER_LASTNAME + data[i].PASSENGER_FIRSTNAME
        });
      }
      _this.restaurants = list;
    },

    querySearchAsync(queryString, cb) {
      let _this = this;
      let restaurants = _this.restaurants;
      let results = queryString ? _this.createStateFilter(queryString) : restaurants;
      clearTimeout(_this.timeout);
      _this.timeout = setTimeout(() => {
        cb(results);
      }, 200 * Math.random());
    },

    createStateFilter(queryString) {
      let _this = this;
      // 匹配结果
      let restaurants = _this.restaurants;
      // 输入值转换大写
      queryString = queryString.toUpperCase();
      let result = restaurants.filter(
        state => state.label.toUpperCase().indexOf(queryString) === 0
      );
      return result;
    },

    handleSelect(item) {
      let _this = this;
      _this.$nextTick(() => {
        _this.search.customerName = item.label;
        _this.search.PASSENGER_PASSPORT = item.value;
      });
    },

    cleanSearch() {
      let _this = this;
      _this.$nextTick(() => {
        _this.search.customerName = "";
        _this.search.PASSENGER_PASSPORT = "";
      });
    },

    // 获取所有客户配置信息
    searchAll() {
      let _this = this;
      get('/api/options/getOptionsAll').then(res => {
        if (res.success) {
          _this.cusOpts = res.data;
        } else {
          this.$message({
            message: res.message,
            type: "error"
          });
        }
      }).catch(err => {
        console.log(err);
      });
    },

    // 查询某个客户的配置信息
    searchByCus() {
      let _this = this;
      if (_this.search.PASSENGER_PASSPORT === "" || null || undefined) {
         _this.searchAll();
      } else {
        let params = {
          t_no: _this.search.PASSENGER_PASSPORT
        };
        post('/api/options/getOptionslist', params).then(res => {
          if (res.success) {
            if (res.data.length === 0) {
                this.$message({
                message: "无配置信息",
                type: "error"
              });
              _this.searchAll();
            } else {
              _this.cusOpts = res.data;
            }
          } else {
            this.$message({
              message: res.message,
              type: "error"
            });
          }
        }).catch(err => {
          console.log(err);
        });
      }
    },

    // 显示编辑界面
    edit(row) {
      let _this = this;
      _this.dialogTitle = "修改";
      _this.dialogShow = true;
      _this.isEdit = true;
      _this.customer = {
        cuslist: row.t_customer + ',' + row.t_name + ',' + row.t_no,
        t_logos: row.t_logos,
        t_url: row.t_url,
        t_email: row.t_email.split(','),
        t_tell: row.t_tell.split(',')
      }
    },

    // 显示新增界面
    addOpt() {
      let _this = this;
      _this.dialogTitle = "添加";
      _this.dialogShow = true;
      _this.isEdit = false;
      _this.customer = {
        cuslist: "",
        t_logos: "",
        t_url: "",
        t_email: [],
        t_tell: []
      };
    },

    // 新增
    create() {
      let _this = this;
      const cusbox = this.$refs["customer"];
      this.$nextTick(() => {
        cusbox.validate(valid => {
          if (valid) {
            let cusl = _this.customer.cuslist.split(',');
            let params = {
              t_name: cusl[1],
              t_no: cusl[2],
              t_customer: cusl[0],
              t_logos: _this.customer.t_logos,
              t_url:  _this.customer.t_url,
              t_email: _this.customer.t_email.toString(),
              t_tell: _this.customer.t_tell.toString(),
              mark: 0
            };
            post('/api/options/addOptions', params).then(res => {
              if (res.success) {
                this.$message({
                  message: res.message,
                  type: "success"
                });
                _this.dialogShow = false;
                _this.searchAll();
              } else {
                this.$message({
                  message: res.message,
                  type: "error"
                });
              }
            }).catch(err => {
              console.log(err);
            });
          } else {
            return false;
          }
        });
      });
    },

    // 修改
    update() {
      let _this = this;
      const cusbox = this.$refs["customer"];
      this.$nextTick(() => {
        cusbox.validate(valid => {
          if (valid) {
            let cusl = _this.customer.cuslist.split(',');
            let params = {
              t_name: cusl[1],
              t_no: cusl[2],
              t_customer: cusl[0],
              t_logos: _this.customer.t_logos,
              t_url:  _this.customer.t_url,
              t_email: _this.customer.t_email.toString(),
              t_tell: _this.customer.t_tell.toString()
            };
            post('/api/options/updateOptions', params).then(res => {
              if (res.success) {
                this.$message({
                  message: res.message,
                  type: "success"
                });
                _this.dialogShow = false;
                _this.searchAll();
              } else {
                this.$message({
                  message: res.message,
                  type: "error"
                });
              }
            }).catch(err => {
              console.log(err);
            });
          } else {
            return false;
          }
        });
      });
    },

    // 删除客户
    del(row) {
      let _this = this;
      let params = {
        t_no: row
      };
      // 删除二次确认
      _this.$confirm("确认删除选中的信息吗？", "提示", {
        type: "warning"
      }).then(() => {
        post('/api/options/delOptions', params).then(res => {
            if (res.success) {
              this.$message({
                message: "删除成功！",
                type: "success"
              });
              _this.searchAll();
            }
          }).catch(err => {
            console.log(err);
          });
      }).catch(() => {
        _this.$message({
          type: "info",
          message: "已取消删除"
        });
      });
    }
  }
};
</script>

<style lang='scss' scoped>
@import "./index.scss";
</style>